define([
    'app',
    'moment',
    'ace-language-tools'
], function(app, moment) {
    app.controller('EditCodeController', function(xContext, $uibModalInstance, $timeout, xUtil, xLocation) {
        var self = this;

        var codeEditor = null;

        self.init = function() {
            var snippet = '', mode = 'text';
            if (xContext.lang == 'curl') {
                var codeLines = [];
                // method
                codeLines.push('curl -X ' + xContext.params.method);
                // url
                codeLines.push(xContext.params.url);
                // headers
                if (_.size(xContext.params.headers) > 0) {
                    if (xContext.params.body && xContext.params.body.type == 'form-data') {
                        var boundary = '----WebKitFormBoundary' + Math.random().toString(36).substring(2);
                        xContext.params.headers['Content-Type'] += '; boundary=' + boundary;
                    }
                    _.forEach(xContext.params.headers, function(value, name) {
                        codeLines.push("-H '" + name + ": " + value + "'");
                    });
                }
                // body
                if (xContext.params.body) {
                    switch (xContext.params.body.type) {
                        case 'form-data':
                            _.forEach(xContext.params.body.data, function(value, name) {
                                codeLines.push("-F '" + name + "=" + value + "'");
                            });
                            break;
                        case 'x-www-form-urlencoded':
                            var query = _.map(xContext.params.body.data, function(value, name) {
                                return name + '=' + value;
                            }).join('&');
                            codeLines.push("-d '" + encodeURI(query) + "'");
                            break;
                        case 'raw':
                            codeLines.push("-d '" + xContext.params.body.data + "'");
                            break;
                        case 'binary':
                        default: break;
                    }
                }
                mode = 'sh';
                snippet = codeLines.join(' \\\n    ');
            } else if (xContext.lang == 'postman') {
                // Postman info
                var info = {
                    name: 'MOCK-v' + moment().format('YYYYMMDDHHmmss'),
                    schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
                };
                // Postman item
                var item = {
                    name: xContext.params.name,
                    request: {
                        method: xContext.params.method,
                        header: [],
                        url: {
                            raw: xContext.params.url,
                            path: [],
                            query: []
                        }
                    }
                };
                // headers
                if (_.size(xContext.params.headers) > 0) {
                    _.forEach(xContext.params.headers, function(value, name) {
                        item.request.header.push({ key: name, value: value});
                    });
                }
                // url
                var location = xLocation.parse(xContext.params.url);
                item.request.url.protocol = location.protocol();
                item.request.url.host = location.host().split(/\./);
                item.request.url.port = location.port();
                // path
                if (location.path()) {
                    item.request.url.path = location.path().split(/\//);
                }
                // query
                var queryParams = location.search();
                if (_.size(queryParams) > 0) {
                    _.forEach(queryParams, function(value, name) {
                        item.request.url.query.push({ key: name, value: value});
                    });
                }
                // body
                if (xContext.params.body) {
                    item.request.body = {};
                    switch (xContext.params.body.type) {
                        case 'form-data':
                            item.request.body.mode = 'formdata';
                        case 'x-www-form-urlencoded':
                            if (!item.request.body.mode) {
                                item.request.body.mode = 'urlencoded';
                            }
                            item.request.body[item.request.body.mode] = _.map(xContext.params.body.data,
                                    function(value, name) {
                                        if (value.indexOf('@') == 0) {
                                            return { key: name, type: 'file' };
                                        }
                                        return { key: name, value: value };
                                    });
                            break;
                        case 'raw':
                            item.request.body.mode = 'raw';
                            item.request.body.raw = xContext.params.body.data;
                            break;
                        case 'binary':
                        default: break;
                    }
                }
                mode = 'json';
                snippet = JSON.stringify({
                    info: info,
                    item: [item]
                }, null, 4);
            }

            // Code editor
            codeEditor = ace.edit('code-editor', {
                mode: 'ace/mode/' + mode,
                theme: 'ace/theme/chrome',
                fontSize: 14,
                wrap: true,
                showPrintMargin: false,
                autoScrollEditorIntoView: true,
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true
            });

            $timeout(function() {
                codeEditor.setValue(snippet, -1);
                codeEditor.resize();
            });

            xUtil.clipboard.copy('#copy-code', function() {
                return codeEditor.getValue();
            });
        }

        self.close = function() {
            $uibModalInstance.close(true);
        }
    });
});
